const app = getApp()
Page({
	data: {
		url: app.globalData.host,
		userInfo: {},
		code: null,
		token: null,
		infos: null,
	},
	onLoad(){
		wx.setNavigationBarTitle({
			title: "我的"
		})
	},
	onShow() {
		this.getUserInfo();
	},
	// 从后台获取用户信息
	getUserInfo(){
		wx.showLoading({title: '加载中…'});
		app.request({
			url: '/app/user',
			method: 'GET',
			success: res => {
				if(res.code === 200){
					this.setData({
						userInfo: res.data
					})
				}
			}
		})
		wx.hideLoading();
	},
	// button 获取
	getPhoneNumber (e) {
		wx.login({
			success: info => {
				let iv = e.detail.iv;
				let code = info.code;
				let encryptedData = e.detail.encryptedData;
				let infos = {
					iv: e.detail.iv,
					code: info.code,
					encryptedData: e.detail.encryptedData
				}
				//手机号和验证码验证略
				let errMsg = e.detail.errMsg;
				if(errMsg == 'getPhoneNumber:ok'){
					this.setData({
						infos: infos
					})
					this.getPhone();
				}
			}
		})
	},
	getPhone(){
		if(this.data.inofs !== null && this.data.token !== null){
			let infos = this.data.infos
			app.request({
				url: '/app/binding',
				method: 'POST',
				data: infos,
				success: res => {
					if(res.code == 200){
						this.setData({
							[`userInfo.phone`]: res.data.phone
						})
						this.getUserInfo();
					}else{
						//弹出错误信息
						wx.showToast({
							title: res.data.msg,
							icon:'error'
						})
					}
				},
				fail: err => {
					console.log(err)
				}
			})
		}
	},
	getUserProfile(e) {
		let that = this;
		wx.login({
			success: code => {
				this.setData({
					code: code.code
				})
			}
		})
		wx.getUserProfile({
			desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: info => {
				this.setData({
					[`userInfo.avatar`]: info.userInfo.avatarUrl,
					[`userInfo.nickName`]: info.userInfo.nickName
				})
				wx.showLoading({title: '加载中…'});
				app.request({
					url: '/app/login',
					method: 'POST',
					data: {
						code: this.data.code,
						iv: info.iv,
						signature: info.signature,
						encryptedData: info.encryptedData,
					},
					success: res => {
						wx.setStorageSync('token',res.token);
						this.setData({
							token: res.token
						})
						this.getPhone();
					}
				})
				wx.hideLoading();
			}
		})
	},
	toPage(e){
		let url = e.currentTarget.dataset.url
		wx.navigateTo({
			url: url
		})
	},
	// 充值
	recharge(){
		wx.showToast({
			title: "余额功能尚未启用",
			icon: 'none',//图标，支持"success"、"loading" 
			duration: 2000,//提示的延迟时间，单位毫秒，默认：1500 
			mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false 
			success:function(){},
			fail:function(){},
			complete:function(){}
		})
	}
})
